package com.doctor.windflower_doctor.fragment;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.doctor.windflower_doctor.R;
import com.doctor.windflower_doctor.actionBeen.QuestionAction;
import com.doctor.windflower_doctor.adapter.MyQuestionAdapter;
import com.doctor.windflower_doctor.adapter.PopAdapter;
import com.doctor.windflower_doctor.db.SharedPreferencesDB;
import com.doctor.windflower_doctor.entity.QuestionBeen;
import com.doctor.windflower_doctor.fragment.MenuFragment.SLMenuListOnItemClickListener;
import com.doctor.windflower_doctor.http.callback.HttpRequestCallBack;
import com.doctor.windflower_doctor.http.parser.RefreshIntent;
import com.doctor.windflower_doctor.http.parser.RefreshMiss;
import com.doctor.windflower_doctor.http.parser.RefreshMyShow;
import com.doctor.windflower_doctor.http.parser.RefreshShow;
import com.doctor.windflower_doctor.http.parser.impl.JsonParser;
import com.doctor.windflower_doctor.http.request.HttpRequest;
import com.doctor.windflower_doctor.http.request.HttpRequestParams;
import com.doctor.windflower_doctor.http.response.HttpResponseInfo;
import com.doctor.windflower_doctor.polling.PollingService;
import com.doctor.windflower_doctor.polling.PollingUtils;
import com.doctor.windflower_doctor.util.Constent;
import com.doctor.windflower_doctor.view.LoadingDialog;
import com.doctor.windflower_doctor.view.PullToCustomListView;
import com.doctor.windflower_doctor.view.PullToCustomListView.OnAutoLoadBottomListener;
import com.doctor.windflower_doctor.view.PullToRefreshBase.OnRefreshListener;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

public class MyQuestionHallFragment extends BaseFragment implements
		SLMenuListOnItemClickListener, RefreshIntent {
	private PullToCustomListView cuto_listView;
	private ListView lv_message;
	private MyQuestionAdapter adapter;
	private boolean flag = true;
	private int s, m, a;
	private int height;
	private int nums;
	private String final_id;
	private TextView text_title;
	private ImageView right_img, right_red;
	private LoadingDialog loadingDialog;
	private Fragment currentFragment;
	private RelativeLayout pop_num;
	private TextView tv_num;
	private TextView tv_answer;
	private RelativeLayout layout;
	private List<Map<String, String>> moreList;
	private ListView lvPopupList;
	public static MyQuestionHallFragment isTance;
	public static String _id = "";
	public static String id;
	private boolean isAccept;
	private List<QuestionBeen> list;
	private int last_item = -1;
	private LinearLayout oldView;
	private PopAdapter popAdapter;
	private RelativeLayout backLayout;
	private Context context;
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			adapter.setText(String.valueOf(msg.arg1), String.valueOf(msg.arg2));
		};
	};

	@Override
	protected View setConentView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.fragment_question, container, false);
	}

	@Override
	protected void getSaveData(Bundle savedInstanceState) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void processLogic() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		adapter = new MyQuestionAdapter(getActivity());
		lv_message.setAdapter(adapter);
		adapter.setShow(new RefreshShow() {

			@Override
			public void isRefreshs(boolean isRefresh) {
				// TODO Auto-generated method stub

				if (isRefresh) {

					show();
				}
			}
		});
		adapter.setMyShow(new RefreshMyShow() {

			@Override
			public void isRefreshs(boolean isMyRefresh) {
				// TODO Auto-generated method stub
				if (isMyRefresh) {
					myShow();
				}
			}
		});
		adapter.setIntent(new RefreshIntent() {

			@Override
			public void isRefresh(boolean is) {
				// TODO Auto-generated method stub
				if (is)
					selectItem(0, "我的问题");
			}
		});
		adapter.setMiss(new RefreshMiss() {

			@Override
			public void isMiss(boolean ismiss) {
				// TODO Auto-generated method stub
				if (ismiss) {
					lvPopupList.setVisibility(View.GONE);
				}
			}
		});
		cuto_listView.setOnRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				adapter.clear();
				pop_num.setVisibility(View.GONE);
				getQuestion(_id, 1);
			}
		});
		cuto_listView
				.setOnAutoLoadBottomListener(new OnAutoLoadBottomListener() {

					@Override
					public void onBottomLoad() {
						// TODO Auto-generated method stub
						loadQuestion();
					}
				});
		layout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				lvPopupList.setVisibility(View.GONE);
			}
		});
	}

	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		getQuestion("", 1);
	}

	@Override
	protected void findViews(View view) {
		// TODO Auto-generated method stub
		context = getActivity();
		cuto_listView = (PullToCustomListView) view
				.findViewById(R.id.listView1);
		isAccept = SharedPreferencesDB.getInstance(getActivity())
				.getIsAcceptQuestion();
		isTance = this;
		lv_message = cuto_listView.getRefreshableView();
		backLayout = (RelativeLayout) view.findViewById(R.id.question);
		right_img = (ImageView) getActivity().findViewById(R.id.right_img);
		right_red = (ImageView) getActivity().findViewById(R.id.iv_ti);
		text_title = (TextView) getActivity().findViewById(R.id.text_title);
		loadingDialog = new LoadingDialog(getActivity());
		pop_num = (RelativeLayout) view.findViewById(R.id.pop_top);
		tv_num = (TextView) view.findViewById(R.id.tv_new_num);
		tv_answer = (TextView) view.findViewById(R.id.tv_answer);
		layout = (RelativeLayout) view.findViewById(R.id.question_bar);
		tv_answer.setVisibility(View.GONE);
		cuto_listView.setSelected(false);
		lvPopupList = (ListView) view.findViewById(R.id.lv_pop);
		iniPopupWindow();
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {

					while (flag) {
						Thread.sleep(1000);

						s--;
						if (s == -1) {
							s = 59;
							m--;
							if (m == -1) {
								m = 0;
							}
						}
						Message message = handler.obtainMessage();
						message.arg1 = s;
						message.arg2 = m;
						handler.sendMessage(message);
						if (s == 0 && m == 0) {
							flag = false;
						}
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}).start();
		getType();

	}

	public void post() {
		// TODO Auto-generated method stub
		if (list != null) {
			/*
			 * if(i%2==0){ lvPopupList.setVisibility(View.VISIBLE); i++;} else {
			 * lvPopupList.setVisibility(View.GONE); i++; }
			 */
			if (lvPopupList.getVisibility() == View.GONE) {
				lvPopupList.setVisibility(View.VISIBLE);
			} else {
				lvPopupList.setVisibility(View.GONE);
			}
		}
	}

	private void iniPopupWindow() {
		popAdapter = new PopAdapter(getActivity());
		lvPopupList.setAdapter(popAdapter);
		lvPopupList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				_id = list.get(position)._id;
				getQuestion(_id, 1);
				LinearLayout layout = (LinearLayout) view;
				layout.setBackgroundResource(R.drawable.selector);
				if (last_item != -1 && last_item != position) {// 如果已经单击过条目并且上次保存的item位置和当前位置不同
					oldView.setBackgroundResource(0);// 把上次选中的样式去掉
				}
				popAdapter.setSelector(position);
				oldView = layout;// 把当前的条目保存下来
				last_item = position;// 把当前的位置保存下来
				lvPopupList.setVisibility(View.GONE);
				popAdapter.notifyDataSetChanged();
			}
		});

	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		nums = 0;
		PollingUtils.stopPollingService(getActivity(), PollingService.class,
				PollingService.ACTION);
	}

	public void show() {
		View vi = LayoutInflater.from(context).inflate(
				R.layout.fragment_question, null);
		View view1 = LayoutInflater.from(context).inflate(R.layout.pop_rob,
				null);
		DisplayMetrics dm = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
		height = dm.heightPixels;// 高度
		final PopupWindow pop = new PopupWindow(view1,
				LayoutParams.MATCH_PARENT, height / 11 * 5);
		RelativeLayout layout_pop = (RelativeLayout) vi
				.findViewById(R.id.question);
		pop.showAtLocation(layout_pop, Gravity.CENTER, 0, 0);
		new Handler().postDelayed(new Runnable() {
			public void run() {

				pop.dismiss();
			}
		}, 2000);
	}

	public void myShow() {
		View vi = LayoutInflater.from(getActivity()).inflate(
				R.layout.fragment_question, null);
		View view2 = LayoutInflater.from(getActivity()).inflate(
				R.layout.pop_show, null);
		DisplayMetrics dm = new DisplayMetrics();
		getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
		height = dm.heightPixels;// 高度
		final PopupWindow pop = new PopupWindow(view2,
				LayoutParams.MATCH_PARENT, height);
		RelativeLayout layout_pop = (RelativeLayout) vi
				.findViewById(R.id.question);
		pop.showAtLocation(layout_pop, Gravity.CENTER, 0, 0);
		Button button = (Button) view2.findViewById(R.id.submit);
		button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				pop.dismiss();
			}
		});
	}

	public void showNum(int num) {
		pop_num.setVisibility(View.VISIBLE);
		tv_num.setText(num + "条新提问");
		tv_num.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				adapter.clear();
				pop_num.setVisibility(View.GONE);
				getQuestion(_id, 1);
			}
		});
	}

	private void getType() {
		String url = Constent.URL + Constent.ASK_QUESTIONTYPE + "?doctorId="
				+ SharedPreferencesDB.getInstance(getActivity()).getDocotorId();
		HttpMethod method = HttpMethod.GET;
		HttpRequestCallBack<QuestionAction> requestCallBack = new HttpRequestCallBack<QuestionAction>(
				new JsonParser(), QuestionAction.class) {

			@Override
			protected void handleResult(
					HttpResponseInfo<QuestionAction> responseInfo) {
				// TODO Auto-generated method stub
				if (responseInfo.success != null) {
					if (responseInfo.success.success) {
						list = responseInfo.success.data.classifications;
						popAdapter.addData(list);
						popAdapter.notifyDataSetChanged();

					}
				}
			}

			@Override
			protected void handleError(HttpException e, String msg) {
				// TODO Auto-generated method stub
				if (msg.equals("HttpHostConnectException")) {
					Toast.makeText(getActivity(), "网络请求失败", Toast.LENGTH_SHORT)
							.show();

				} else
					Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT)
							.show();

			}
		};
		HttpRequestParams params = new HttpRequestParams(method, url,
				requestCallBack);
		HttpRequest.send(params);
	}

	public void getNum(String id) {
		String url = Constent.URL + Constent.ASK_NEWQUESTION + "?doctorId="
				+ SharedPreferencesDB.getInstance(getActivity()).getDocotorId()
				+ "&id=" + id + "&classification=" + _id;
		HttpMethod method = HttpMethod.GET;
		HttpRequestCallBack<QuestionAction> requestCallBack = new HttpRequestCallBack<QuestionAction>(
				new JsonParser(), QuestionAction.class) {

			@Override
			protected void handleResult(
					HttpResponseInfo<QuestionAction> responseInfo) {
				// TODO Auto-generated method stub
				if (responseInfo.success != null) {
					if (responseInfo.success.success) {
						int num = responseInfo.success.data.numberOfNewQuestion;
						if (num > 0) {
							nums = num;
							showNum(nums);
						} else {
							pop_num.setVisibility(View.GONE);
						}
					}
				}
			}

			@Override
			protected void handleError(HttpException e, String msg) {
				// TODO Auto-generated method stub
				PollingUtils.stopPollingService(getActivity(),
						PollingService.class, PollingService.ACTION);
			}
		};
		HttpRequestParams params = new HttpRequestParams(method, url,
				requestCallBack);
		HttpRequest.send(params);
	}

	private void loadQuestion() {
		String url = Constent.URL + Constent.ASK_QUESTIONHALL + "?doctorId="
				+ SharedPreferencesDB.getInstance(getActivity()).getDocotorId()
				+ "&size=10&id=" + final_id + "&classification=" + _id;
		HttpMethod requestMethod = HttpMethod.GET;
		HttpRequestCallBack<QuestionAction> requestCallBack = new HttpRequestCallBack<QuestionAction>(
				new JsonParser(), QuestionAction.class) {

			@Override
			protected void handleResult(
					HttpResponseInfo<QuestionAction> responseInfo) {
				cuto_listView.onLoadBottomComplete();
				if (responseInfo.success != null) {
					if (responseInfo.success.success) {
						List<QuestionBeen> list = responseInfo.success.data.questions;

						if (list == null) {
							Toast.makeText(getActivity(), "网络请求失败",
									Toast.LENGTH_SHORT).show();
						} else {
							if (list.size() > 0) {

								adapter.addData(list,
										responseInfo.success.data.timeLimit,
										isAccept);
								adapter.notifyDataSetChanged();
								if (adapter.getCount() > 0)
									final_id = ((QuestionBeen) adapter
											.getItem(adapter.getCount() - 1)).id;

							} else {
								cuto_listView.onLoadBottomEnd();
								Toast.makeText(getActivity(), "已经到底部了",
										Toast.LENGTH_SHORT).show();
							}
						}
					}
				}
			}

			@Override
			protected void handleError(HttpException e, String msg) {
				// TODO Auto-generated method stub
				cuto_listView.onLoadBottomEnd();
				if (msg.equals("HttpHostConnectException")) {
					Toast.makeText(getActivity(), "网络请求失败", Toast.LENGTH_SHORT)
							.show();

				} else
					Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT)
							.show();
			}
		};
		HttpRequestParams params = new HttpRequestParams(requestMethod, url,
				requestCallBack);
		HttpRequest.send(params);
	}

	public void getQuestion(String type, final int x) {
		String url = Constent.URL + Constent.ASK_QUESTIONHALL + "?doctorId="
				+ SharedPreferencesDB.getInstance(getActivity()).getDocotorId()
				+ "&size=10" + "&classification=" + type;

		HttpMethod requestMethod = HttpMethod.GET;
		HttpRequestCallBack<QuestionAction> requestCallBack = new HttpRequestCallBack<QuestionAction>(
				new JsonParser(), QuestionAction.class) {

			@Override
			protected void handleResult(
					HttpResponseInfo<QuestionAction> responseInfo) {
				loadingDialog.close();
				if (responseInfo.success != null) {
					if (responseInfo.success.success) {
						adapter.clear();
						List<QuestionBeen> list = responseInfo.success.data.questions;
						adapter.addData(list,
								responseInfo.success.data.timeLimit, isAccept);
						a = responseInfo.success.data.timeLimit;
						if (a >= 120) {
							m = 2;
							s = a - 120;
						} else if (a >= 60) {
							m = 1;
							s = a - 60;
						} else {
							m = 0;
							s = a;
						}
						adapter.notifyDataSetChanged();
						if (adapter.getCount() > 0) {
							layout.setVisibility(View.GONE);
							id = ((QuestionBeen) adapter.getItem(0)).id;
							final_id = ((QuestionBeen) adapter.getItem(adapter
									.getCount() - 1)).id;

							getNum(id);
							if (id != null) {
								PollingUtils.startPollingService(getActivity(),
										5, PollingService.class,
										PollingService.ACTION, id);
							}
						} else {
							layout.setVisibility(View.VISIBLE);
						}
					}
				}
				cuto_listView.onRefreshDownComplete();

			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				if (x == 1)
					loadingDialog.show();

			}

			@Override
			protected void handleError(HttpException e, String msg) {
				// TODO Auto-generated method stub
				loadingDialog.close();
				layout.setVisibility(View.VISIBLE);
				PollingUtils.stopPollingService(getActivity(),
						PollingService.class, PollingService.ACTION);
				if (msg.equals("HttpHostConnectException")) {
					Toast.makeText(getActivity(), "网络请求失败", Toast.LENGTH_SHORT)
							.show();
				}

				else
					Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT)
							.show();
			}
		};
		HttpRequestParams params = new HttpRequestParams(requestMethod, url,
				requestCallBack);
		HttpRequest.send(params);
	}

	@Override
	public void onDestroyView() {
		// TODO Auto-generated method stub
		PollingUtils.stopPollingService(getActivity(), PollingService.class,
				PollingService.ACTION);
		super.onDestroyView();
		_id = "";
		id = "";
	}

	@Override
	public void selectItem(int position, String title) {
		// TODO Auto-generated method stub
		Fragment fragment = null;
		text_title.setText(title);
		switch (position) {
		case 0:
			fragment = MyQueationFragment.getInstance(new Bundle());
			right_img.setVisibility(View.INVISIBLE);
			right_red.setVisibility(View.GONE);
			break;
		default:
			break;
		}
		if (fragment != null) {
			FragmentManager fragmentManager = getActivity()
					.getSupportFragmentManager();
			FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();
			if (currentFragment != null)
				fragmentTransaction.hide(currentFragment);
			if (!fragment.isAdded()) {
				fragmentTransaction.replace(R.id.content, fragment);
				fragmentTransaction.replace(R.id.left_menu, new MenuFragment());// 更新选中menu
			} else {
				fragmentTransaction.show(fragment);
			}
			currentFragment = fragment;
			fragmentTransaction.commit();
			getActivity().setTitle(title);
		}
	}

	@Override
	public void isRefresh(boolean is) {
		// TODO Auto-generated method stub

	}

}